<template>
  <el-dialog v-model="dialogFormVisible" :title="props.formData?.dialogTitle" :width="props.formData?.dialogWidth">
    <el-form :model="props.formData!.columns" label-width="120px"  :inline="props.formData?.inline">
      <template v-for="(item) in props.formData?.columns">
        <div v-if="item.type == 'select'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-select clearable v-model="item.value" :placeholder="'选择' + item.label" style="width: 240px" :disabled="item.isEdit">
              <el-option v-for="opt in item.options" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'switch'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-switch v-model="item.value" inline-prompt
                       :active-value="item.activeValue" :activeText="item.activeText"
                       :inactive-text="item.inactiveText" :inactive-value="item.inactiveValue">
            </el-switch>
          </el-form-item>
        </div>
        <!--多图上传-->
        <div v-else-if="item.type == 'upload'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <UploadImg v-model:img-list="item.value"></UploadImg>
          </el-form-item>
        </div>
        <!--单图上传-->
        <div v-else-if="item.type == 'avatar'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-upload class="avatar-uploader" :action="item.action"
                       :on-success="handleAvatarSuccess" :show-file-list="false">
              <img v-if="imageUrl" :src="imageUrl" class="avatar"  alt=""/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'photo'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-upload class="avatar-uploader" :action="item.action"
                       :on-success="handlePhotoSuccess" :show-file-list="false">
              <img v-if="photoUrl" :src="photoUrl" class="avatar"  alt=""/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'button'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-button plain @click="selectProducts">关联商品</el-button>
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'double'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-input-number v-model="item.value" :precision="2" :step="item.min" :max="item.max" />
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'number'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-input-number v-model="item.value" style="width: 240px" :min="0" :max="99999" :disabled="item.isEdit" autocomplete="off" />
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'textarea'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-input v-model="item.value" style="width: 240px" :autosize="{ minRows: item.minRows, maxRows: item.maxRows }" type="textarea"
                :placeholder="item.placeholder"
            />
          </el-form-item>
        </div>
        <div v-else-if="item.type == 'richText'">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <Editor v-model:content="item.value" @set-content="setContent"></Editor>
          </el-form-item>
        </div>
        <div v-else v-show="item.isShow">
          <el-form-item :label="item.label" :label-width="item.width" v-if="item.isShow">
            <el-input v-model="item.value" style="width: 240px" :disabled="item.isEdit" :placeholder="item.placeholder" autocomplete="off" />
          </el-form-item>
        </div>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">返回</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 关联商品对话框 -->
  <el-dialog v-model="selectProductVisible" title="选择关联商品">
    <el-card>
      <template #header>
        <el-input
            v-model="searchData"
            style="max-width: 600px"
            placeholder="请输入搜索内容"
            class="input-with-select"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="Select" style="width: 115px">
              <el-option label="商品名称" name="productName" />
              <el-option label="商品类别" name="categoryName" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="fetchInitialProducts()" />
          </template>
        </el-input>
      </template>
      <template #default>
        <div>
          <el-card  v-for="product in products" :key="product.productId" style="margin-bottom: 20px;" shadow="hover">
            <el-descriptions :title="`店铺：`+ product.merchantName" :column="4" border direction="vertical">

              <el-descriptions-item :rowspan="2" :width="80" label="图片" align="center">
                <el-image style="width: 100px; height: 100px" :src="getImgUrl(product.imageUrls.split(',')[0])" />
              </el-descriptions-item>
              <el-descriptions-item label="名称" align="center">{{ product.productName }}</el-descriptions-item>
              <el-descriptions-item label="价格" align="center">{{ product.price }}</el-descriptions-item>
              <el-descriptions-item label="操作" align="center">
                <el-button type="primary" size="default" @click="selectProduct(product)">选择</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </template>
    </el-card>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import UploadImg from "./UploadImg.vue";
  import Editor from "@/components/Editor.vue";
  import {Plus, Search} from "@element-plus/icons-vue";
  import {getAllProducts} from "@/api/pruduct";
  import {getImgUrl} from "@/utils/common.ts";
  import {ElMessage} from "element-plus";

  const dialogFormVisible = ref(false)  // 弹窗显示或隐藏
  // 店铺LOGO图片地址
  const imageUrl = ref('')
  // 营业执照图片地址
  const photoUrl = ref('')

  enum operationType {
    ADD = 1,
    EDIT = 2,
  }

  // 接收父组件传递的参数
  const props = defineProps({
    formData: Object,
  })

  const showDialog = (newValue: boolean) => {
    dialogFormVisible.value = newValue;
    console.log("父组件传入数据：",props.formData)
  };

  // 暴露方法给父组件
  defineExpose({
    showDialog
  });

  // 声明自定义事件
  const emit = defineEmits(['confirm', 'cancel'])

  const confirm = () => {
    if (props.formData!.dialogTitle.concat('编辑')) {
      emit('confirm',operationType.EDIT)
    } else {
      emit('confirm',operationType.ADD)
    }
    dialogFormVisible.value = false
    imageUrl.value = ''
    photoUrl.value = ''
  }

  const cancel = () => {
    emit('cancel')
    dialogFormVisible.value = false
    imageUrl.value = ''
    photoUrl.value = ''
  }

  let url = 'http://localhost:8018/file/image?imageName='

  watch(() => props.formData, (newFormData: any) => {
    if (newFormData && newFormData.columns) {
      initializeImageUrl(newFormData);
    }
  }, { deep: true }); // 深度监听以捕获内部属性的变化

  // 初始化图片地址
  const initializeImageUrl = (formData: any) => {
    formData.columns.forEach((item: any) => {
      if (item.prop === 'merchantLogo' && item.value) {
        imageUrl.value = url + item.value;
      }
      if (item.prop === 'businessLicense' && item.value) {
        photoUrl.value = url + item.value;
      }
    });
  };

  const handleAvatarSuccess = (res: any) => {
    if (res.code == 200) {
      props.formData!.columns.forEach((item: any)=>{
        if(item.prop == 'merchantLogo'){
          item.value = res.data.url
          imageUrl.value = url + item.value;
        }
      })
      ElMessage.success("头像设置成功");
    } else {
      ElMessage.error(res.describe);
    }
  };

  const handlePhotoSuccess = (res: any) => {
    if (res.code == 200) {
      props.formData!.columns.forEach((item: any)=>{
        if(item.prop == 'businessLicense'){
          item.value = res.data.url
          imageUrl.value = url + item.value;
        }
      })
      ElMessage.success("上传成功");
    } else {
      ElMessage.error(res.describe);
    }
  };

  /**
   * =======================关联商品==================================
   */
  const selectProductVisible = ref(false)
  // 选择关联商品
  const selectProducts = () =>{
    selectProductVisible.value = true
  }

  const searchData = ref('')
  const select = ref('')

  const selectProduct = (product: Product) => {
    selectProductVisible.value = false
    props.formData!.columns.forEach((item: any)=>{
      if(item.prop == 'productId'){
        item.value = product.productId
      }
    })
  }

  const setContent = (content: string) => {
    props.formData!.columns.forEach((item: any)=>{
      if(item.prop == 'content'){
        item.value = content
      }
    })
  }

  interface Product {
    productId: number;
    productName: string;
    imageUrls: string;
    merchantName: string;
    price: number;
  }

  const products: Product[] = [];

  // 获取初始商品列表
  const fetchInitialProducts = async () => {
    const res = await getAllProducts({});
    if (res.code === 0) {
      products.push(...res.data);
    }
  };
  fetchInitialProducts();

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>